package com.yc.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.QueryResult;
import com.yc.R_Code;
import com.yc.Result;
import com.yc.entities.BloodSugarGluce;
import com.yc.entities.BloodSugarPatientInfo;
import com.yc.entities.custom.*;
import com.yc.mapper.BloodSugarGluceMapper;
import com.yc.mapper.BloodSugarPatientInfoMapper;
import com.yc.service.BloodSugarPatientInfoService;
import io.swagger.models.auth.In;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 患者信息表 服务实现类
 * </p>
 *
 * @author kuakha
 * @since 2021-04-12
 */
@Service
public class BloodSugarPatientInfoServiceImpl extends ServiceImpl<BloodSugarPatientInfoMapper, BloodSugarPatientInfo> implements BloodSugarPatientInfoService {

    @Autowired
    private BloodSugarGluceMapper bloodSugarGluceMapper;

    @Override
    public int insertPatient(BloodSugarPatientInfo patientInfo) {
        return this.baseMapper.insertPatient(patientInfo);
    }

    @Override
    public List<AppHomePageUserBean> appHomePageAllPatientInfo(BloodSugarPatientInfo bloodSugarPatientInfo) {
        return this.baseMapper.appHomePageAllPatientInfo(bloodSugarPatientInfo);
    }

    @Override
    public List<AppHomePageUserBean> appHomePageToBeMeasuredInfo(BloodSugarPatientInfo bloodSugarPatientInfo) {
        return this.baseMapper.appHomePageToBeMeasuredInfo(bloodSugarPatientInfo);
    }

    @Override
    public List<AppHomePageUserBean> abnormalDataByUser(BloodSugarPatientInfo bloodSugarPatientInfo) {
        return this.baseMapper.abnormalDataByUser(bloodSugarPatientInfo);
    }

    @Override
    public List<AppHomePageUserBean> appHomePageConcernsPatientInfo(BloodSugarPatientInfo bloodSugarPatientInfo) {
        return this.baseMapper.appHomePageConcernsPatientInfo(bloodSugarPatientInfo);
    }

    @Override
    public Result getAllBarcodeInfo(Integer deaId, Integer departmentId, Integer current, Integer size) {
        Page<Integer> page = new Page<>(current == null ? 0 : current, size == null ? 10 : size);
        List<CustomBarCodeResponseBean> allRoleInfo = this.baseMapper.getAllRoleInfo(page, deaId, departmentId);
        if (allRoleInfo.size() >= 1) {
            return Result.ok().total((int) page.getTotal()).data(allRoleInfo);
        } else {
            return Result.ok().code(R_Code.R_NULL_DATA_FAIL);
        }
    }

    @Override
    public Result getAllDataInfo(CustomDataQueryRequestBean customDataQueryRequestBean) {
        Page<CustomDataQueryRequestBean> page = new Page<>(customDataQueryRequestBean.getCurrent(), customDataQueryRequestBean.getSize());
        List<CustomDataQueryResponseBean> allRoleInfo = this.baseMapper.getAllDataInfo(page, customDataQueryRequestBean);
        if (allRoleInfo.size() >= 1) {
            return Result.ok().total((int) page.getTotal()).data(allRoleInfo);
        } else {
            return Result.ok().code(R_Code.R_NULL_DATA_FAIL);
        }
    }

    @Override
    public Result getAllOutPatientInfo(CustomOutPatientQueryRequestBean customOutPatientQueryRequestBean) {
        Page<CustomOutPatientQueryRequestBean> page = new Page<>(customOutPatientQueryRequestBean.getCurrent(), customOutPatientQueryRequestBean.getSize());
        List<CustomOutPatientQueryResponseBean> allRoleInfo = this.baseMapper.getAllOutPatientInfo(page, customOutPatientQueryRequestBean);
        if (allRoleInfo.size() >= 1) {
            return Result.ok().total((int) page.getTotal()).data(allRoleInfo);
        } else {
            return Result.error().code(R_Code.R_NULL_DATA_FAIL);
        }
    }

    @Override
    public Result getAllIndexInfo(CustomIndexQueryRequestBean customIndexQueryRequestBean) {
        Result ok = Result.ok();
//        Page<CustomIndexQueryRequestBean> page = new Page<>(customIndexQueryRequestBean.getCurrent(), customIndexQueryRequestBean.getSize());
//        List<CustomIndexQueryResponseBean> allRoleInfo = this.baseMapper.getAllIndexInfo(page, customIndexQueryRequestBean);
//        customIndexQueryRequestBean.setCurrent(customIndexQueryRequestBean.getCurrent() * customIndexQueryRequestBean.getSize() - customIndexQueryRequestBean.getSize());
        List<CustomIndexQueryResponseBean> allRoleInfo = this.baseMapper.getAllIndexInfo(customIndexQueryRequestBean);
        List<Map<String, Object>> numDatas = new ArrayList<>();
//        concernUserId "是否已经关注 1:已关注  0:未关注"
//        gluceStatus "血糖值状态 0-正常 1-偏高，2-偏低"
//        dutStatus "是否待测 1:待测  0:全部已测"
        List<CustomIndexQueryResponseBean> abnormalData = allRoleInfo.stream().filter(c -> ("1".equals(c.getGluceStatus()) || "2".equals(c.getGluceStatus()))).collect(Collectors.toList());
        List<CustomIndexQueryResponseBean> dutPerson = allRoleInfo.stream().filter(c -> "1".equals(c.getDutStatus())).collect(Collectors.toList());
        List<CustomIndexQueryResponseBean> attentionPatient = allRoleInfo.stream().filter(c -> "1".equals(c.getConcernUserId())).collect(Collectors.toList());
        HashMap<String, Object> allNumberPersons = new HashMap<>();
        allNumberPersons.put("id", "0");
        allNumberPersons.put("num", allRoleInfo.stream().filter(f1 -> null != (f1.getUserId())).count());
        allNumberPersons.put("title", "全部人数");
        HashMap<String, Object> abnormalDataNum = new HashMap<>();
        abnormalDataNum.put("id", "1");
        abnormalDataNum.put("num", abnormalData.stream().filter(f1 -> null != (f1.getUserId())).count());
        abnormalDataNum.put("title", "异常数据");
        HashMap<String, Object> dutPersons = new HashMap<>();
        dutPersons.put("id", "2");
        dutPersons.put("num", dutPerson.stream().filter(f1 -> null != (f1.getUserId())).count());
        dutPersons.put("title", "待测人数");
        HashMap<String, Object> attentionPatients = new HashMap<>();
        attentionPatients.put("id", "3");
        attentionPatients.put("num", attentionPatient.stream().filter(f1 -> null != (f1.getUserId())).count());
        attentionPatients.put("title", "关注患者");
        //全部人数
        numDatas.add(allNumberPersons);
        //异常数据
        numDatas.add(abnormalDataNum);
        //待测人数
        numDatas.add(dutPersons);
        //关注患者
        numDatas.add(attentionPatients);
        ok.data("numData", numDatas);
        //            0:全部人数 1:异常数据 2:待测人数 3:关注患者
        List<CustomIndexQueryResponseBean> customIndexQueryResponseBeans = new ArrayList<>();
        if (allRoleInfo.size() >= 1) {
            switch (customIndexQueryRequestBean.getDataType()) {
                case "0":
                    customIndexQueryResponseBeans.addAll(allRoleInfo);
                    break;
                case "1":
                    customIndexQueryResponseBeans.addAll(abnormalData);
                    break;
                case "2":
                    customIndexQueryResponseBeans.addAll(dutPerson);
                    break;
                case "3":
                    customIndexQueryResponseBeans.addAll(attentionPatient);
                    break;
                default:
                    return Result.error();
            }
            QueryResult<CustomIndexQueryResponseBean> queryResult = new QueryResult<>();
            if (customIndexQueryResponseBeans.size() <= customIndexQueryRequestBean.getSize()){
                queryResult.setList(customIndexQueryResponseBeans);
                queryResult.setPageSize(customIndexQueryRequestBean.getSize());
                queryResult.setTotal(customIndexQueryResponseBeans.size());
                queryResult.setPageNum(customIndexQueryRequestBean.getCurrent());
            }
            else if (CollectionUtils.isNotEmpty(customIndexQueryResponseBeans)) {
                int startIndex = (customIndexQueryRequestBean.getCurrent() - 1) * customIndexQueryRequestBean.getSize();
                int endIndex = Math.min(startIndex + customIndexQueryRequestBean.getSize(), customIndexQueryResponseBeans.size());
                List<CustomIndexQueryResponseBean> ts = customIndexQueryResponseBeans.subList(startIndex, endIndex);
                queryResult.setList(ts);
                queryResult.setPageSize(customIndexQueryRequestBean.getSize());
                queryResult.setTotal(customIndexQueryResponseBeans.size());
                queryResult.setPageNum(customIndexQueryRequestBean.getCurrent());
            }
            if (customIndexQueryResponseBeans.size() == 0){
                HashMap<String, Object> map = new HashMap<>();
                map.put("data",new ArrayList<>().add(new CustomIndexQueryResponseBean()));
                ok.data("data", map);
                return ok.total(customIndexQueryResponseBeans.size());
            }else {
                return ok.total(customIndexQueryResponseBeans.size()).data(queryResult.getList());
            }
        } else {
            return Result.ok().code(R_Code.R_NULL_DATA_FAIL).data(numDatas);
        }
    }

    @Override
    public CustomPatientInfoResponseBean getPatientById(Integer id) {
        return this.baseMapper.getPatientById(id);
    }

    @Override
    public int savePatientInto(CustomPatientSaveRequestBean customPatientSaveRequestBean) {
        return this.baseMapper.savePatientInto(customPatientSaveRequestBean);
    }

    @Override
    public Result getIndexUserBloodGlucoseInfo(Integer id, Integer current, Integer size, String startTime, String endTime) {
//        Page<Integer> page = new Page<>(current == null ? 0 : current, size == null ? 10 : size);
//        List<GluceDataTable> gluceDataByDate = this.baseMapper.getIndexUserBloodGlucoseInfo(page, id, startTime, endTime);
        if (current == null) {
            current = 1;
        }
        if (size == null) {
            size = 10;
        }
        List<GluceDataTable> gluceDataByDate = this.baseMapper.getIndexUserBloodGlucoseInfo(id, startTime, endTime);
        List<GluceDataTable> data = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(gluceDataByDate)) {
            gluceDataByDate.forEach(gluceDataTable -> {
                List<BloodSugarGluce> sugarGluces = new ArrayList<>();
                IntStream.rangeClosed(0, 9).forEach(attr -> {
                    BloodSugarGluce b = new BloodSugarGluce();
                    b.setGluceAttr(attr);
                    b.setBloodGluceValue("--");
//                    b.setGluceValue(null);
                    sugarGluces.add(b);
                });
                GluceDataTable gluceData = new GluceDataTable();
                String gluceExamtime = gluceDataTable.getGluceExamtime();
                gluceData.setGluceExamtime(gluceExamtime);
                List<BloodSugarGluce> bloodSugarGluces = gluceDataTable.getBloodSugarGluces();
                sugarGluces.forEach(s -> {
                    bloodSugarGluces.forEach(n -> {
                        if (s.getGluceAttr().equals(n.getGluceAttr())) {
//                            s.setGluceValue(n.getGluceValue());
                            s.setBloodGluceValue(n.getGluceValue().toString());
                            s.setGluceState(n.getGluceState());
                        }
                    });
                });
                gluceData.setBloodSugarGluces(sugarGluces);
                data.add(gluceData);
            });
        }
        LambdaQueryWrapper<BloodSugarGluce> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(BloodSugarGluce::getGluceUserid, id);
        Integer total = bloodSugarGluceMapper.selectCount(wrapper);
        List<BloodSugarGluce> bloodSugarPatientInfos = bloodSugarGluceMapper.selectList(wrapper);
        List<BigDecimal> glucedDta = new ArrayList<>();
        bloodSugarPatientInfos.forEach(i -> {
            glucedDta.add(i.getGluceValue());
        });
        Map<String, Object> map = new HashMap<>();
        if (glucedDta.size() > 0) {
            BigDecimal max = Collections.max(glucedDta);
            BigDecimal min = Collections.min(glucedDta);
            long normal = bloodSugarPatientInfos.stream().filter(f1 -> 0 == f1.getGluceState()).count();
            long high = bloodSugarPatientInfos.stream().filter(f1 -> 1 == f1.getGluceState()).count();
            long low = bloodSugarPatientInfos.stream().filter(f1 -> 2 == f1.getGluceState()).count();
            map.put("total", total);
            map.put("max", max);
            map.put("min", min);
            map.put("normal", normal);
            map.put("high", high);
            map.put("low", low);
        }
        List<GluceDataTable> collect = data.stream().sorted(Comparator.comparing(GluceDataTable::getGluceExamtime).reversed()).collect(Collectors.toList());

        QueryResult<GluceDataTable> queryResult = new QueryResult<>();
        if (collect.size() <= size){
            queryResult.setList(collect);
            queryResult.setPageSize(size);
            queryResult.setTotal(collect.size());
            queryResult.setPageNum(current);
        }
        else if (CollectionUtils.isNotEmpty(collect)) {
            int startIndex = (current - 1) * size;
            int endIndex = Math.min(startIndex + size, size);
            List<GluceDataTable> ts = collect.subList(startIndex, endIndex);
            queryResult.setList(ts);
            queryResult.setPageSize(size);
            queryResult.setTotal(size);
            queryResult.setPageNum(current);
        }
        if (queryResult.getList().size() >= 1) {
            return Result.ok().total(queryResult.getTotal()).data(queryResult.getList()).data("dataNum", map);
        } else {
            return Result.ok().code(R_Code.R_NULL_DATA_FAIL);
        }
    }

    @Override
    public BloodSugarPatientInfo getBloodSugarPatientInfoByType(String toHospitalNum, String phone, String bedNum, String departmentId ,String doctorId) {
        return this.baseMapper.getBloodSugarPatientInfoByType(toHospitalNum, phone, bedNum, departmentId ,doctorId);
    }

    @Override
    public Result getIndexUserOutInHospitalRecord(String hospitalNum, Integer current, Integer size) {
        Page<Integer> page = new Page<>(current == null ? 0 : current, size == null ? 10 : size);
        List<CustomOutInRecordResponseBean> list = this.baseMapper.getIndexUserOutInHospitalRecord(page, hospitalNum);
        list.forEach(f1 -> {
            if (StringUtils.isBlank(f1.getOutSugarNum())) {
                f1.setOutSugarNum("--");
            }
        });
        if (list.size() >= 1) {
            return Result.ok().data(list).total((int) page.getTotal());
        } else {
            return Result.ok().code(R_Code.R_NULL_DATA_FAIL);
        }
    }

    @Override
    public int updatePatientOutHospital(Integer id, Double outSugarNum) {
        BloodSugarPatientInfo bloodSugarPatientInfo = new BloodSugarPatientInfo();
        bloodSugarPatientInfo.setId(id);
        bloodSugarPatientInfo.setTheHospitalStatus("1");
        bloodSugarPatientInfo.setOutSugarNum(outSugarNum);
        bloodSugarPatientInfo.setOutHospitalTime(new Date());
        return this.baseMapper.updateById(bloodSugarPatientInfo);
    }

    @Override
    public Result getIndexUserBloodGlucoseDetail(Integer id, String time, String attr) {
        if (StringUtils.isNotBlank(attr)) {
//            gluceAttr2.bloodGluceValue
            if ("gluceExamtime".equals(attr)) {
                return null;
            }
            attr = attr.split("\\.")[0].split("r")[1];
        }
        List<Map<String, Object>> list = this.baseMapper.getIndexUserBloodGlucoseDetail(id, time, attr);
        if (list.size() >= 1) {
            return Result.ok().data(list);
        } else {
            return Result.ok().code(R_Code.R_NULL_DATA_FAIL);
        }
    }

    @Override
    public Result getDataUserLineChartInfo(Integer id, String startTime, String endTime) {
        String[] attrs = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        List<String> attrList = Arrays.stream(attrs).collect(Collectors.toList());
        List<CustomChartResponseBean> customChartResponseBeans = new ArrayList<>();
        attrList.forEach(f1 -> {
            List<CustomDataBean> customDataBean = this.baseMapper.getDataUserLineChartInfo(id, f1, startTime, endTime);
            CustomChartResponseBean customChartResponseBean = new CustomChartResponseBean();
            customChartResponseBean.setTimeQuantum(customDataBean);
            switch (f1) {
                case "0":
                    customChartResponseBean.setLabel("空腹");
                    break;
                case "1":
                    customChartResponseBean.setLabel("早餐前");
                    break;
                case "2":
                    customChartResponseBean.setLabel("早餐后");
                    break;
                case "3":
                    customChartResponseBean.setLabel("午餐前");
                    break;
                case "4":
                    customChartResponseBean.setLabel("午餐后");
                    break;
                case "5":
                    customChartResponseBean.setLabel("晚餐前");
                    break;
                case "6":
                    customChartResponseBean.setLabel("晚餐后");
                    break;
                case "7":
                    customChartResponseBean.setLabel("睡前");
                    break;
                case "8":
                    customChartResponseBean.setLabel("凌晨");
                    break;
                case "9":
                    customChartResponseBean.setLabel("随机");
                    break;
                default:
                    break;
            }
            customChartResponseBeans.add(customChartResponseBean);
        });

        return Result.ok().data(customChartResponseBeans);
    }


}